package context

import (
	"context"
	"log"
	"sync"
)

type ArgsDownlaod struct {
	Cid  string
	Path string
	Date string
}
type ReplyDownload struct {
	Res bool
}

type Downlaod interface {
	rpcGetDownload(ctx context.Context, args *ArgsDownlaod, reply *ReplyDownload) error
}

type FtpDownload struct {
	args  *ArgsDownlaod
	reply *ReplyDownload
}

func (f *FtpDownload) FormatCustidDate() string {
	panic("implement me")
}

func (f *FtpDownload) ReadRemoteFileContent(path string) string {
	panic("implement me")
}

func (f *FtpDownload) ParseFilter(s string) (string, error) {
	panic("implement me")
}

func (f *FtpDownload) Save() error {
	panic("implement me")
}

func (f *FtpDownload) SyncDatabase() (bool, error) {
	panic("implement me")
}

//嵌入魔板 自己是具体的业务逻辑 魔板是外部初始化的第一个门面处理
//
type SftpDownload struct {
	args  *ArgsDownlaod
	reply *ReplyDownload
	*template
}

// template->donwaloder
// template
// template->impl->interface->impl
// template->proxy->impl->inter
// http-impl
func NewDownloader(args *ArgsDownlaod, reply *ReplyDownload) Downlaod {
	sftp := &SftpDownload{args: args, reply: reply}
	sftp.template = &template{
		impl: sftp,
	}
	return sftp
}

func (s SftpDownload) FormatCustidDate() string {
	panic("implement me")
}

func (s SftpDownload) ReadRemoteFileContent(path string) string {
	panic("implement me")
}

func (s SftpDownload) ParseFilter(s2 string) (string, error) {
	panic("implement me")
}

func (s SftpDownload) Save() error {
	panic("implement me")
}

func (s SftpDownload) SyncDatabase() (bool, error) {
	panic("implement me")
}

type StepDownload interface {
	FormatCustidDate() string                 //格式化获取对应的下载文件路径 cid_日期.txt
	ReadRemoteFileContent(path string) string //读取远程文件内容
	ParseFilter(string) (string, error)       //解析过滤filter
	Save() error                              //保存文件到服务器
	SyncDatabase() (bool, error)              //同步到数据到数据库
}

type template struct {
	impl StepDownload
}

func (t *template) rpcGetDownload(ctx context.Context, args *ArgsDownlaod, reply *ReplyDownload) error {
	var wg sync.WaitGroup
	//格式化下载的路径
	path := t.impl.FormatCustidDate()
	//
	content := t.impl.ReadRemoteFileContent(path)
	//读取远程内容
	content, err := t.impl.ParseFilter(content)
	//进行过滤
	if err != nil {
		return err
	}
	err = t.impl.Save() //保存到本地信息
	if err != nil {
		return err
	}
	var err2 error
	wg.Add(1)
	go func() {
		defer wg.Done()
		isTrue, er := t.impl.SyncDatabase() //同步数据库
		if !isTrue {
			log.Println("插入数据库失败")
			err2 = er
		}
	}()
	wg.Wait()
	if err2 != nil {
		return err
	}
	return nil

}
